package com.turman.common.net.config

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import okhttp3.*
import okio.Buffer
import java.lang.reflect.Type

class CniaoInterceptor:Interceptor {
    companion object {
        private val gson:Gson = GsonBuilder()
            .enableComplexMapKeySerialization()
            .create()
        private val mapType: Type = object :TypeToken<Map<String,Any>>(){}.type
    }


    override fun intercept(chain: Interceptor.Chain): Response {
        val originRequest:Request = chain.request()

        //添加的公共header,封装clientInfo，deviceInfo等，也可以post请求中，自定义header添加
        val attachHeaders:MutableList<Pair<String,String>> = mutableListOf(
            "appid" to NET_CONFIG_APPID,
            "platform" to "android",
            "timestamp" to System.currentTimeMillis().toString(),
//            "brand" to DeviceUtils.getManufacturer()
        )

        // 这里读取登录后token
        val token = ""
        if (token.isNotBlank()) {
            attachHeaders.add("token" to token)
        }

        //get的请求参数拼装到header
        originRequest.url.queryParameterNames.forEach{
            attachHeaders.add(it to (originRequest.url.queryParameter(it)?:""))
        }

        //post的请求参数
        val requestBody:RequestBody? = originRequest.body
        if (originRequest.method == "POST") {
            //表单形式提交的数据
            if (requestBody is FormBody) {
                for (i:Int in 0 until requestBody.size) {
                    attachHeaders.add(requestBody.name(i) to requestBody.value(i))
                }
            }

            //json形式提交的数据,需要将requestBody反序列化为map application/json
            if (requestBody?.contentType()?.type == "application" && requestBody.contentType()?.subtype == "json") {
                kotlin.runCatching {
                    val buffer = Buffer()
                    requestBody.writeTo(buffer)
                    buffer.readByteString().utf8()
                }.onSuccess {
                    val map:Map<String, Any> = gson.fromJson<Map<String,Any>>(it, mapType)
                    map.forEach{entry->
                        attachHeaders.add(entry.key to entry.value.toString())
                    }
                }
            }
        }

        //所有参数都必须是非空的参数
        val signValue:String = attachHeaders
            .sortedBy { it.first }
            .joinToString("&"){"${it.first}=${it.second}"}
            .plus("&appkey=$NET_CONFIG_APPKEY")

        val newBuilder:Request.Builder  = originRequest.newBuilder()
            .cacheControl(CacheControl.FORCE_NETWORK)

        attachHeaders.forEach { newBuilder.header(it.first,it.second) }
        newBuilder.header("sign",/*md5加密的signValue*/signValue)

        if (originRequest.method == "POST" && requestBody!=null) {
            newBuilder.post(requestBody)
        } else {
            newBuilder.get()
        }

        return chain.proceed(newBuilder.build())

    }
}





















